#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   file.py
@Time    :   2024/01/04 15:34:30
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
import os
from pathlib import Path
from datetime import datetime
from typing import List
from urllib.parse import unquote
from django.http import FileResponse, HttpResponse
from django.shortcuts import get_object_or_404
from django.db import transaction

from big_event.settings import BASE_DIR, MEDIA_URL
from ninja import Field
from ninja import File
from ninja import ModelSchema, Query, Router, Schema
from ninja.files import UploadedFile
from ninja.pagination import paginate
from system.models import FileModel
from utils.crud import create, delete, retrieve, update
from utils.auth import BaseFilters,MyPagination
from utils.response import R

router = Router()


class Filters(BaseFilters):
    name: str = Field(None, alias="name")


class FileSchema(Schema):
    name: str = Field(None, alias="name")
    url: str = Field(None, alias="url")


class FileSchemaOut(ModelSchema):
    class Config:
        model = FileModel
        model_fields = ['id','name','save_name', 'url', 'size']
       

@router.get("", summary="文件列表",response=List[FileSchemaOut])
@paginate(MyPagination)
def list_file(request, filters: Filters = Query(...)):
    qs = retrieve(request, FileModel, filters)
    return qs


@router.get("/all", summary="全部文件",response=List[FileSchemaOut])
def all_list_file(request):
    qs = retrieve(request, FileModel)
    return qs


@router.post("/upload", summary="上传文件",response=FileSchemaOut)
def upload_file(request, file: UploadedFile = File(...)):
    current_date = datetime.now().strftime('%Y%m%d%H%M%S%f')
    current_ymd = datetime.now().strftime('%Y%m%d')
    file_name = current_date + '_' + file.name.replace(' ', '_')
    file_path = os.path.join(MEDIA_URL, 'files', current_ymd)
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    file_url = os.path.join(file_path, file_name)
    with open(file_url, 'wb') as f:
        f.write(file.read())
    # url地址为文件夹名称+文件名称
    url = f"files/{current_ymd}/{file_name}"
    # 创建数据库条目
    with transaction.atomic():
        data = {
            'name': file.name,
            'size': file.size,
            'save_name': file_name,
            'url': url,
        }
        qs = create(request, data, FileModel)
    return qs


@router.post("/download",summary="下载文件")
def download_file(request, data: FileSchema):
    file_path = str(BASE_DIR) + unquote(data.url)
    r = FileResponse(open(file_path, "rb"), as_attachment=True)
    return r


@router.get("/{id}", summary="文件详情",response=FileSchemaOut)
def get_file(request, id: int):
    qs = get_object_or_404(FileModel, id=id)
    return qs


@router.delete("/{id}",summary="删除文件",response=R)
def delete_file(request, id: int):
    delete(id, FileModel)
    return R(msg="文件删除成功")

        

@router.get("/image/{id}", summary="获取图像",auth=None)
def get_image_file(request, id: int):
    qs = get_object_or_404(FileModel, id=id)
    url = Path(qs.url.url)
    file_path = str(BASE_DIR) + str(url)
    return HttpResponse(open(file_path , "rb"), content_type='image/png')

